package com.fc.mall.portal.controller;

import com.alibaba.druid.util.StringUtils;
import com.fc.mall.base.object.Result;
import com.fc.mall.kdniao.constants.Shipper;
import com.fc.mall.kdniao.domain.LogisticTraceReq;
import com.fc.mall.kdniao.domain.LogisticTraceResp;
import com.fc.mall.kdniao.service.KDNiaoService;
import com.fc.mall.model.OmsCartItem;
import com.fc.mall.model.OmsOrder;
import com.fc.mall.portal.domain.ConfirmOrderResult;
import com.fc.mall.portal.domain.ImmediatelyOrderParam;
import com.fc.mall.portal.domain.OmsOrderFromFans;
import com.fc.mall.portal.domain.OrderParam;
import com.fc.mall.portal.dto.OmsOrderQueryParam;
import com.fc.mall.portal.service.OmsPortalOrderService;
import com.fc.mall.portal.util.IpUtils;
import com.fc.mall.portal.vo.OmsOrderVO;
import com.fc.mall.portal.vo.OrderCountByStatusVO;
import com.fc.mall.portal.wechat.WxPaymentUtil;
import com.fc.mall.portal.wechat.dto.WXPaymentResponse;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单管理Controller
 * Created by dobuy on 2018/8/30.
 */
@RestController
@Api(tags = "OmsPortalOrderController",description = "订单管理")
@RequestMapping("/order")
@SuppressWarnings("Duplicates")
public class OmsPortalOrderController {

    @Autowired
    private KDNiaoService kdNiaoService;

    @Autowired
    private OmsPortalOrderService portalOrderService;

    @ApiOperation("根据购物车信息生成确认单信息")
    @RequestMapping(value = "/generateConfirmOrder",method = RequestMethod.POST)
    @ResponseBody
    public Result generateConfirmOrder(@RequestParam(value = "cartIds") String cartIds){
        ConfirmOrderResult confirmOrderResult = portalOrderService.generateConfirmOrder(cartIds);
        return Result.success(confirmOrderResult);
    }

    @ApiOperation("根据购物车信息生成订单")
    @RequestMapping(value = "/generateOrder",method = RequestMethod.POST)
    @ResponseBody
    public Result generateOrder(@RequestBody OrderParam orderParam, @RequestParam(value = "cartIds") String cartIds){
        return portalOrderService.generateOrder(orderParam, cartIds);
    }

    @ApiOperation("根据商品信息生成确认单信息")
    @RequestMapping(value = "/generateConfirmOrder/immediately",method = RequestMethod.POST)
    @ResponseBody
    public Result generateConfirmOrder(@RequestBody OmsCartItem omsCartItem){
        List<OmsCartItem> omsCartItemList = new ArrayList<>();
        omsCartItemList.add(omsCartItem);
        ConfirmOrderResult confirmOrderResult = portalOrderService.generateConfirmOrder(omsCartItemList);
        return Result.success(confirmOrderResult);
    }

    @GetMapping("{orderId}")
    public Result getOrderById(@PathVariable Long orderId)
    {
        OmsOrderVO omsOrder = portalOrderService.getOrderVOById(orderId);
        return Result.success(omsOrder);
    }

    @ApiOperation("根据商品信息立即生成订单")
    @RequestMapping(value = "/generateOrder/immediately",method = RequestMethod.POST)
    @ResponseBody
    public Result generateOrder(@RequestBody ImmediatelyOrderParam immediatelyOrderParam){
        List<OmsCartItem> omsCartItemList = new ArrayList<>();
        omsCartItemList.add(immediatelyOrderParam.getOmsCartItem());
        return portalOrderService.generateOrder(immediatelyOrderParam.getOrderParam(), omsCartItemList);
    }

    @ApiOperation("微信回调")
    @RequestMapping(value = "/wxpayment/notifications/{notificationType}",method = RequestMethod.POST)
    public void wxPayNotification(@PathVariable("notificationType") String notificationType,
                                  HttpServletRequest request, HttpServletResponse response) {
        try {
            String notifyXml = IOUtils.toString(request.getInputStream(), Charset.forName("UTF-8"));
            Map<String, String> notificationMap = WxPaymentUtil.xmlToMap(notifyXml);
            if ("FAIL".equals(notificationMap.get("return_code"))) {
                wxResponse(WxPaymentUtil.fail(notificationMap.get("return_msg")), response);
                return;
            }

            if ("refund".equals(notificationType)) {
                portalOrderService.refundCallback(notificationMap);
            }
            wxResponse(WxPaymentUtil.ok(), response);
        } catch (Exception e) {
            wxResponse(WxPaymentUtil.fail(""), response);
        }
    }

    private void wxResponse(String respXml, HttpServletResponse response) {
        try {
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(respXml.getBytes());
            out.flush();
        } catch (Exception e) {

        }
    }

    @ApiOperation("支付成功的回调")
    @RequestMapping(value = "/wxpayment/notify",method = RequestMethod.POST)
    public void wxNotify(HttpServletRequest request, HttpServletResponse response)
    {
        BufferedReader br = null;
        BufferedOutputStream out = null;

        try
        {
            br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            //sb为微信返回的xml
            String notifyXml = sb.toString();
            System.out.println("=================================");
            System.out.println(notifyXml);
            System.out.println("=================================");
            String respXml = portalOrderService.payCallback(notifyXml);
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(respXml.getBytes());
            out.flush();
        }
        catch (Exception e)
        {

        }
    }

    @ApiOperation("自动取消超时订单")
    @RequestMapping(value = "/cancelTimeOutOrder",method = RequestMethod.POST)
    @ResponseBody
    public Result cancelTimeOutOrder(){
        return portalOrderService.cancelTimeOutOrder();
    }

    @ApiOperation("取消单个超时订单")
    @RequestMapping(value = "/cancelOrder",method = RequestMethod.POST)
    @ResponseBody
    public Result cancelOrder(Long orderId){
        portalOrderService.sendDelayMessageCancelOrder(orderId);
        return Result.success();
    }

    @ApiOperation("查询订单")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Result queryOrder(OmsOrderQueryParam queryParam,
                             @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum){
        PageInfo<OmsOrderVO> orderList = portalOrderService.list(queryParam, pageSize, pageNum);
        return Result.success(orderList);
    }

    @ApiOperation("订单状态数量")
    @RequestMapping(value = "/countOrderCountByStatus", method = RequestMethod.GET)
    @ResponseBody
    public Result countOrderCountByStatus(){
        OrderCountByStatusVO results = portalOrderService.countOrderByStatus();
        return Result.success(results);
    }

    @GetMapping("/test/pay/{orderNumber}")
    public Result testPay(@PathVariable String orderNumber)
    {
        portalOrderService.paySuccess(orderNumber);
        return Result.success();
    }

    @ApiOperation("订单支付")
    @PostMapping("/payment/{orderNumber}")
    public Result paymentOrder(@PathVariable String orderNumber, HttpServletRequest request) {

        if (StringUtils.isEmpty(orderNumber)) {
            return  Result.failed("订单编号不能为空");
        }
        String spbillCreateIp = IpUtils.getIpAddr(request);
        WXPaymentResponse response = portalOrderService.unifiedOrder(orderNumber, spbillCreateIp);
        return  Result.success(response);
    }

    @ApiOperation("订单物流查询")
    @PostMapping("/trackLogistic")
    @ResponseBody
    public Result trackLogistic(@RequestBody LogisticTraceReq logisticTraceReq) {
        LogisticTraceResp resp = kdNiaoService.trackLogistic(logisticTraceReq);
        return Result.success(resp);
    }

    @ApiOperation("根据订单号查询订单物流信息")
    @GetMapping("/trackLogisticByOrderId/{orderId}")
    @ResponseBody
    public Result trackLogisticByOrderId(@PathVariable Long orderId) {
        OmsOrder omsOrder = portalOrderService.getById(orderId);
        if (omsOrder != null && omsOrder.getDeliveryCompany() != null && omsOrder.getDeliverySn() != null) {
            LogisticTraceReq traceReq = new LogisticTraceReq();
            traceReq.setShipperCode(Shipper.getCode(omsOrder.getDeliveryCompany()));
            traceReq.setLogisticCode(omsOrder.getDeliverySn());
            LogisticTraceResp resp = kdNiaoService.trackLogistic(traceReq);
            resp.setShipperName(omsOrder.getDeliveryCompany());
            return Result.success(resp);
        } else {
            return Result.success();
        }
    }

    @GetMapping("/fans/list")
    @ResponseBody
    public Result handleGetFansOrder()
    {
        List<OmsOrderFromFans> fansOrderList = portalOrderService.getfansOrderList();
        return  Result.success(fansOrderList);
    }

    @PutMapping("{orderNumber}/status/{statusCode}")
    public Result handleUpDateOrderStatus(@PathVariable(name = "orderNumber") String orderNumber,
                                          @PathVariable(name = "statusCode") Integer statusCode)
    {
        portalOrderService.updateOrderStatus(orderNumber, statusCode);
        return Result.success();
    }
}
